﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace CVM.Data.Repositories.Base
{
    public abstract class RepositoryBase : IRepository
    {
        protected string TableName { get; set; }        

        #region Generic Wrappers
        public virtual void Add(Entities.DataEntityBase entity)
        {
            using(var conn = Connection.GetInstance())
            {
                conn.Open();
                var command = AddCommand(entity);
                SqlCommand cmd = new SqlCommand(command, conn);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

        public virtual IList<Entities.DataEntityBase> GetAll()
        {
            using (var conn = Connection.GetInstance())
            {
                conn.Open();
                var command = GetAllCommand();
                SqlCommand cmd = new SqlCommand(command, conn);
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                conn.Close();

                IList<Entities.DataEntityBase> results = new List<Entities.DataEntityBase>();

                foreach (DataRow row in dt.Rows)
                {
                    Entities.DataEntityBase r = GetItem(row);
                    results.Add(r);
                }

                return results;
            }
        }

        public virtual Entities.DataEntityBase Get(int ID)
        {
            throw new NotImplementedException();
        }

        public virtual void Delete(int ID)
        {
            using (var conn = Connection.GetInstance())
            {
                conn.Open();
                var command = DeleteCommand(ID);
                SqlCommand cmd = new SqlCommand(command, conn);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
        #endregion

        protected abstract Entities.DataEntityBase GetItem(DataRow row);

        #region Generic Commands
        protected abstract string AddCommand(Entities.DataEntityBase _dataEntity);
        protected virtual string GetAllCommand()
        {
            var mask = "select * from {0}";
            var ret = string.Format(mask, TableName);
            return ret;
        }
        protected virtual string DeleteCommand(int ID)
        {
            var mask = "delete from {0} where ID= " + ID; ;
            var ret = string.Format(mask, TableName);
            return ret;
        }
        #endregion
    }
}
